//var gid = $("#gid").val();
$(document).ready(
		function() {
			lang = $("display-lang").val();
			var ds_type = $("#ds_type").val();
			var ds_id = $("#ds_id").val();
			var relation_id = $("#relation_id").val();
			var user = $("#user").val();
			var dtitle;
			if(lang == 'en'){
				dtitle = "On Loading";
			}else if(lang == 'zh'){
				dtitle = "正在加载";
			}
			$("#onloading").dialog({
				bgiframe : true,
				autoOpen : false,
				draggable : false,
				closeOnEscape : false,
				closeText : false,
				resizable : false,
				width : 400,
				title : dtitle,
				modal : true
			});
			$("#onloading").parent().appendTo("#dialog_target");
			$('a.ui-dialog-titlebar-close').hide();
			$("#backButton").click(function(){
				$("#tabs").tabs("option", "selected", 0);  
			});
			$("#saveButton").live(
					"click",
					function() {
						var sels = new Array();
						$("#role_sel input[type='checkbox']").each(
								function() {
									if ($(this).attr("checked") == "checked") {
										var a = $(this).parent().children(
												"input[type='text']").attr(
												"value");
										var v = $(this).attr("name");
										var item = new Object();
										item["v"] = v;
										item["role"] = a;
										sels.push(item);
									}
								});
						if (checkRoles(sels) == true) {
							var name = $("#rel_name input").attr("value");
							if (checkRelName(name) == true) {
								save(relation_id, sels, name, user);
							} else {
								if(lang == 'en'){
									alert("ERROR: Please check relation name.");
								}else if(lang == 'zh'){
									alert("错误: 请确认是否已填写关系名。");
								}
								
							}
						} else {
							if(lang == 'en'){
								alert("ERROR: Please check role selection.");
							}else if(lang == 'zh'){
								alert("错误: 请确认是否已设置角色。");
							}
						}
					});

			$("#testButton").live(
					"click",
					function() {
						var sels = new Array();
						$("#role_sel input[type='checkbox']").each(
								function() {
									if ($(this).attr("checked") == "checked") {
										var a = $(this).parent().children(
												"input[type='text']").attr(
												"value");
										var v = $(this).attr("name");
										var item = new Object();
										item["v"] = v;
										item["role"] = a;
										sels.push(item);
									}
								});
						if (checkRoles(sels) == true) {
							test(relation_id, sels, ds_type, ds_id);
						} else {
							if(lang == 'en'){
								alert("ERROR: Please check role selection.");
							}else if(lang == 'zh'){
								alert("错误: 请确认是否已设置角色。");
							}
						}
					});
		});

$("#tabs_2_role").click(function() {
	var ds_type = $("#ds_type").val();
	var ds_id = $("#ds_id").val();
	var relation_id = $("#relation_id").val();

	getRelationName(relation_id);
	getPattern_role(relation_id);
	getRelRoles(relation_id);
	getResult_role(relation_id, ds_type, ds_id);
});


function getRelationName(relation_id) {
	var data = {};
	data["id"] = relation_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationInfo",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var name = result["name"];
			$("#rel_name_input").attr("value", name);
		}
	});
}

function save(relation_id, sels, name, user) {
	var data = {};
	data["id"] = relation_id;
	data["roles"] = sels;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/changeRoles",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var data = {};
			data["id"] = relation_id;
			data["name"] = name;
			data["user"] = user;
//			data["gid"] = $("#gid").val();
			data = JSON.stringify(data);
			data = ("data=" + encodeURIComponent(data));
			$.ajax({
				url : "/sview/saveRelation",
				async : true,
				data : data,
				dataType : "json",
				type : "post",
				success : function(result) {
					var rs = result["result"];
					if(rs=="OK"){
						if(lang == 'en'){
							alert("Saved.");
						}else if(lang == 'zh'){
							alert("已保存。");
						}
						if (relation_id != 0) {
							window.location.reload();
						} else {
							window.close();
						}
					}else if(rs == "nogid"){
						if(lang == 'en'){
							alert("Failed! group id param missing!");
						}else if(lang == 'zh'){
							alert("失败: 未确定编辑组。");
						}
//						alert("Failed! Session has timed out!")
					}
				}
			});
		}
	});
}

function test(relation_id, sels, ds_type, ds_id) {
	var data = {};
	data["id"] = relation_id;
	data["roles"] = sels;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/changeRoles",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			getPattern_role(relation_id);
			getRelRoles(relation_id);
			getResult_role(relation_id, ds_type, ds_id);
		}
	});
}

function checkRoles(sels) {
	if (sels.length == 0)
		return false;
	var ret = true;
	for ( var i in sels) {
		var role = sels[i]["role"];
		role = role.trim();
		if (role == "") {
			ret = false;
		}
	}
	return ret;
}

function checkRelName(name) {
	var ret = true;
	if (name.trim() == "") {
		ret = false;
	}
	return ret;
}

function getRelRoles(relation_id) {
	var data = {};
	data["id"] = relation_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationRoles",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$("#role_sel").html("");
			var array = result["result"];
			for ( var i = 0; i < array.length; i++) {
				var v_role = array[i];
				var v = v_role["v"];
				var role = v_role["role"];
				var div = $("<div></div>");
				$("#role_sel").append(div);
				var ckbox = $("<input type='checkbox'></input>");
				ckbox.attr("name", v);
				if (role != "") {
					ckbox.attr("checked", "checked");
				}
				div.append(ckbox);
				var span = $("<span></span>");
				span.html(v);
				div.append(span);
				var input = $("<input type='text'></input>");
				input.attr("value", role);
				div.append(input);
			}
		}
	});
}

function getPattern_role(relation_id) {
	var data = {};
	data["id"] = relation_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$.ajax({
		url : "/sview/relationPattern",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			var array = result["result"];
			$("#rel_pattern").html("");
			for ( var i = 0; i < array.length; i++) {
				var triple = array[i];
				var stext = new String(triple["stext"]);
				var ptext = new String(triple["ptext"]);
				var otext = new String(triple["otext"]);
				var s = new String(triple["s"]);
				var p = triple["p"];
				var o = new String(triple["o"]);
				var s_dis = stext;
				var p_dis = ptext;
				var o_dis = otext;
				if (s.indexOf("u") == 0) {
					s_dis = getLocalname(stext);
				}
				p_dis = getLocalname(ptext);
				if (o.indexOf("u") == 0) {
					o_dis = getLocalname(otext);
				}
				var tripleDIV = $("<div class='triple'></div>");
				tripleDIV.attr("s", s);
				tripleDIV.attr("p", p);
				tripleDIV.attr("o", o);
				$("#rel_pattern").append(tripleDIV);
				var disDIV = $("<span></span>");
				disDIV.html("(<span title='" + stext + "'>" + s_dis
						+ "</span>,<span title='" + ptext + "'>" + p_dis
						+ "</span>,<span title='" + otext + "'>" + o_dis
						+ "</span>)");
				tripleDIV.append(disDIV);
			}
		}
	});
}

function getResult_role(relation_id, ds_type, ds_id) {
	var data = {};
	data["id"] = relation_id;
	data["ds_type"] = ds_type;
	data["ds_id"] = ds_id;
	data = JSON.stringify(data);
	data = ("data=" + encodeURIComponent(data));
	$("#onloading").dialog("open");
	$.ajax({
		url : "/sview/relationResult",
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			$("#onloading").dialog("close");
			$("#role_right").html("");
			var table = $("<table></table>");
			$("#role_right").append(table);
			var array = result["result"];
			var tableTitle = array[0];
			var trhead = $("<tr></tr>");
			table.append(trhead);
			for ( var i = 0; i < tableTitle.length; i++) {
				var column = tableTitle[i];
				var vname = column["vname"];
				var th = $("<th></th>");
				th.text(vname);
				trhead.append(th);
			}
			for ( var i = 1; i < array.length; i++) {
				var trbody = $("<tr></tr>");
				table.append(trbody);
				var item = array[i];
				for ( var j = 0; j < item.length; j++) {
					var ele = item[j];
					var v = ele["v"];
					var name = new String(ele["name"]);
					var content = ele["content"];
					var dis = ele["displayName"];//content;
//					if (name.indexOf("u") == 0) {
//						dis = getLocalname(content);
//					}
					var td = $("<td></td>");
					trbody.append(td);
					td.attr("v", v);
					td.attr("name", name);
					var div = $("<span></span>");
					div.attr("title", content);
					div.text(dis);
					td.append(div);
				}
			}
		}
	});
}